package cn.rwklyd.BookKeeping.controller;

import cn.rwklyd.BookKeeping.pojo.Result;
import cn.rwklyd.BookKeeping.pojo.Transaction;
import cn.rwklyd.BookKeeping.pojo.dto.QueryTransactions;
import cn.rwklyd.BookKeeping.pojo.vo.TransactionVO;
import cn.rwklyd.BookKeeping.service.TransactionService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import cn.rwklyd.BookKeeping.pojo.vo.TransactionPageVO;
import cn.rwklyd.BookKeeping.pojo.dto.ReceiptImageDTO;

@RestController
@RequestMapping("/transaction")
@Tag(name = "收支记录管理", description = "收入支出记录的增删查改接口")
@Slf4j
public class TransactionController {

    @Autowired
    private TransactionService transactionService;

    /**
     * 添加收支记录
     */
    @PostMapping("/add")
    @Operation(summary = "添加记录", description = "添加一个新的收入或支出记录，返回新创建记录的ID")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<Long> addTransaction(@RequestBody Transaction transaction) {
        log.info("添加收支记录: {}", transaction);
        return transactionService.addTransaction(transaction);
    }

    /**
     * 删除收支记录
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除记录", description = "根据ID删除收支记录")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<String> deleteTransaction(
            @Parameter(description = "记录ID", required = true)
            @PathVariable Long id) {
        log.info("删除收支记录: {}", id);
        return transactionService.deleteTransaction(id);
    }

    /**
     * 更新收支记录
     */
    @PostMapping("/update")
    @Operation(summary = "更新记录", description = "更新收支记录信息")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<String> updateTransaction(@RequestBody Transaction transaction) {
        log.info("更新收支记录: {}", transaction);
        return transactionService.updateTransaction(transaction);
    }

    /**
     * 更新收支凭证图片
     */
    @PostMapping("/updateReceiptImage")
    @Operation(summary = "更新凭证图片", description = "更新收支记录的凭证图片")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<String> updateReceiptImage(@RequestBody ReceiptImageDTO receiptImageDTO) {
        log.info("更新收支凭证图片: {}", receiptImageDTO);
        return transactionService.updateReceiptImage(receiptImageDTO.getId(), receiptImageDTO.getReceiptImage());
    }

    /**
     * 根据ID获取收支记录
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取记录", description = "根据ID获取收支记录详情")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<TransactionVO> getTransactionById(
            @Parameter(description = "记录ID", required = true)
            @PathVariable Long id) {
        log.info("获取收支记录: {}", id);
        return transactionService.getTransactionVOById(id);
    }

    /**
     * 分页获取收支记录列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页获取记录", description = "分页获取当前用户的收支记录列表，结果按交易时间降序排列（最新的在前），同时返回当月收支统计数据")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<TransactionPageVO> getTransactionList(
            @Parameter(description = "页码") @RequestParam(required = false) Integer page,
            @Parameter(description = "每页大小") @RequestParam(required = false) Integer pageSize) {
        log.info("分页获取收支记录列表: page={}, pageSize={}", page, pageSize);
        return transactionService.getTransactionVOList(page, pageSize);
    }

    /**
     * 多条件查询收支记录
     */
    @PostMapping("/query")
    @Operation(summary = "查询记录", description = "多条件查询收支记录，不传参数则查询当前用户的所有收支记录，结果按交易时间降序排列（最新的在前），同时返回当月收支统计数据")
    @PreAuthorize("hasAuthority('view_users')")
    public Result<TransactionPageVO> queryTransactions(@RequestBody QueryTransactions queryTransactions) {
        log.info("查询收支记录参数: {}", queryTransactions);
        Long id = queryTransactions.getId();
        Long userId = queryTransactions.getUserId();
        Long categoryId = queryTransactions.getCategoryId();
        Long platformId = queryTransactions.getPlatformId();
        String remark = queryTransactions.getRemark();
        Integer page = queryTransactions.getPage() != null ? queryTransactions.getPage() : 1;
        Integer pageSize = queryTransactions.getPageSize() != null ? queryTransactions.getPageSize() : 10;
        
        // 获取日期范围
        LocalDateTime startDate = queryTransactions.getStartDate();
        LocalDateTime endDate = queryTransactions.getEndDate();
        
        // 尝试从时间戳获取日期（兼容旧代码）
        if (startDate == null && queryTransactions.getStartTimestamp() != null) {
            startDate = LocalDateTime.ofInstant(
                java.time.Instant.ofEpochSecond(queryTransactions.getStartTimestamp()), 
                java.time.ZoneId.of("Asia/Shanghai")
            );
        }
        
        if (endDate == null && queryTransactions.getEndTimestamp() != null) {
            endDate = LocalDateTime.ofInstant(
                java.time.Instant.ofEpochSecond(queryTransactions.getEndTimestamp()), 
                java.time.ZoneId.of("Asia/Shanghai")
            );
        }
        
        // 尝试从字符串获取日期（兼容旧代码）
        if (startDate == null && queryTransactions.getStartDateStr() != null && !queryTransactions.getStartDateStr().isEmpty()) {
            try {
                startDate = LocalDateTime.parse(queryTransactions.getStartDateStr(), 
                    java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e) {
                log.warn("开始日期格式错误: {}", queryTransactions.getStartDateStr());
            }
        }
        
        if (endDate == null && queryTransactions.getEndDateStr() != null && !queryTransactions.getEndDateStr().isEmpty()) {
            try {
                endDate = LocalDateTime.parse(queryTransactions.getEndDateStr(), 
                    java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e) {
                log.warn("结束日期格式错误: {}", queryTransactions.getEndDateStr());
            }
        }
        
        log.info("解析后的查询日期范围: startDate={}, endDate={}", startDate, endDate);
        
        return transactionService.queryTransactionVOs(
            id, userId, categoryId, platformId,
            startDate, endDate,
            remark, page, pageSize
        );
    }
} 